import {useAccountStore} from "./AccountStore.ts";
import {defineStore} from "pinia";
import {CacheMap, useCache} from "../utils/CacheUtils.ts";
import type {PriMsgBody, PrivateMessageBody} from "../network/types/PrivateMessage.ts";
import type {SimpleUserInfo} from "../network/types/User.ts";
import {replaceAvatar} from "./UserStore.ts";

const api = () => useAccountStore().getNgaApi().message

export const useMessageStore = defineStore('MessageStore', {
    state: () => ({
        cache: new CacheMap<PrivateMessageBody>(),
        cacheRead: new CacheMap<PriMsgBody>(),
        cacheBlockedUser: new CacheMap<SimpleUserInfo[]>(),
        blockedUser: [] as SimpleUserInfo[],
    }),
    actions: {
        async list(page?: number | undefined, force?: boolean) {
            const userId = useAccountStore().getAccountUserId();
            const key = `list ${userId} ${page}`
            return useCache(this.cache, key, force || false, () => api().list(page))
        },
        async read(mid: number, page?: number | undefined, force?: boolean) {
            const key = `read ${mid} ${page}`
            return useCache(this.cacheRead, key, force || false, () => api().read(mid, page))
        },
        async reply(mid: number, content: string, title: string = "") {
            return api().reply(mid, content, title)
        },
        async new(title: string, content: string, users: string[]) {
            return api().new(title, content, users)
        },
        async kick(mid: number, userId: number) {
            return api().kick(mid, userId)
        },
        async blockAdd(userId: number) {
            return api().blockAdd(userId)
        },
        async blockDel(userId: number) {
            return api().blockDel(userId)
        },
        async blockList(force?: boolean) {
            const userId = useAccountStore().getAccountUserId();
            const key = `${userId}`
            return useCache(this.cacheBlockedUser, key, force || false, () => api().blockList().then((res: SimpleUserInfo[]) => {
                res.forEach(i => i.avatars = i.avatars && i.avatars.map(replaceAvatar))
                return res
            }), 10 * 60)
                .then(res => {
                    this.blockedUser = res;
                    return res
                })
        },

    },
})